//
//  MyInfoViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/11/30.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "MyInfoViewController.h"
#import "MyInfoTableViewCell.h"
#import "AvatarTableViewCell.h"
#import "SexViewController.h"
#import "AgeViewController.h"
#import "NicknameViewController.h"
#import "PublicGetUserInfoApi.h"
#import "PublicSetUserInfoApi.h"
//#import "GetUserInfoApi.h"
//#import "SetUserInfoApi.h"
#import "NSDate+DateTools.h"
//#import "WFPhotosViewController.h"

@interface MyInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSArray *dataSource;

@property(nonatomic,strong) UIButton *exitButton;
@property (nonatomic, strong) UIImagePickerController * imagePicker; // 系统图片框架
@property (strong, nonatomic) NSMutableDictionary *userInfoDic;
@property (strong, nonatomic) UIImageView *imageView;

@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getUserInfomation];
    
}

#pragma mark --- 点击事件
- (void)didClickExitButton
{
    [[AlertViewManager shareManager] initWithTitle:@"提示" message:@"您确定要退出登录？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
        if (buttonIndex == 1)
        {
            [SVProgressHUD showWithStatus:@"正在退出中..."];
            [[AppDelegate defaultService] signOut];
        }
    }];
}

#pragma mark - 事件处理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"buttonindex===%ld",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            
        {
            [self formcamera];
            
        }
            break;
        case 1:
            
        {
            [self formphoto];
        }
            break;
            
        default:
            break;
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        _imagePicker = imagePicker;
        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
        {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [self presentViewController:imagePicker animated:YES completion:^{ }];
            }];
            
        }
        else{
            
            [self.navigationController presentViewController:imagePicker animated:YES completion:^{ }];
        }
    }else{
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{

    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    _imagePicker = imagePicker;
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self presentViewController:imagePicker animated:YES completion:^{ }];
        }];
        
    }
    else{
        
        [self.navigationController presentViewController:imagePicker animated:YES completion:^{ }];
    }
}

#pragma mark - private methods -
- (UIImagePickerController *)creatImagePickVCWithSourceType:(UIImagePickerControllerSourceType)sourceType{
    
    UIImagePickerController *imagePickVC = [[UIImagePickerController alloc]init];
    
    //设置选取的照片是否可编辑
    imagePickVC.allowsEditing = YES;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"模拟器无法打开相机");
            return nil;
        }
    }
    //设置相册呈现的样式
    imagePickVC.sourceType =  UIImagePickerControllerSourceTypeCamera;
    imagePickVC.delegate = self;
    
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self presentViewController:imagePickVC animated:YES completion:^{ }];
        }];
        
    }
    else{
        
        [self.navigationController presentViewController:imagePickVC animated:YES completion:^{ }];
    }
   
    return imagePickVC;
}

#pragma mark - UIImagePickerControllerDelegate
// 完成选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    PublicSetUserInfoApi * setApi = [[PublicSetUserInfoApi alloc] initWithDic:@{@"image":PorPath}];
    [setApi dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        if ([[request responseJSONObject][@"errcode"] intValue] == 0) {
            PublicGetUserInfoApi * userInfoApi = [[PublicGetUserInfoApi alloc] init];
            [userInfoApi dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
                [userInfoApi analyseResponseObject];
                [self.tableView reloadData];
                [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            } failure:nil];
        }
    } failure:nil];
    
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)updateUserInfo
{
    PublicSetUserInfoApi *api = [[PublicSetUserInfoApi alloc] initWithDic:_userInfoDic];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
//        NSDictionary *dic = request.responseJSONObject;
        PublicGetUserInfoApi * userInfoApi = [[PublicGetUserInfoApi alloc] init];
        [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            [userInfoApi analyseResponseObject];
            [self userInfoDic];
            [self.tableView reloadData];
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfo" object:nil];
        } failure:^(YTKBaseRequest *request) {
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }];
    } failure:nil];
    
}

- (NSString *)getAgeWithDateString:(NSString *)dateString
{
    NSArray *valueList = [dateString componentsSeparatedByString:@"-"];
    NSDate *date = [NSDate date];
    NSString *nowString = [date formattedDateWithFormat:@"YYYY"];
    NSString *age = [NSString stringWithFormat:@"%i",[nowString intValue] - [valueList.firstObject intValue]];
    if ([nowString isEqualToString:age])
    {
        return @"1";
    }
    return age;
}



- (NSMutableDictionary *)userInfoDic
{
    if (!_userInfoDic) {
        _userInfoDic = [[NSMutableDictionary alloc]init];
    }
    
    NSArray *array = @[@"nickname",@"username",@"sex"
                       ,@"height",@"weight",@"birthday",@"image",@"wsy_uid"];
    NSDictionary *infoDic = EXRACT_OBJECT(INFODIC);
    for (NSString *key in array)
    {
        if ([infoDic[key]length] == 0)
        {
            [_userInfoDic setValue:@"" forKey:key];
        }
        else
        {
            [_userInfoDic setValue:infoDic[key] forKey:key];
        }
    }
    
    return _userInfoDic;
}

- (void)getUserInfomation
{
    PublicGetUserInfoApi * userInfoApi = [[PublicGetUserInfoApi alloc] init];
    [userInfoApi dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [userInfoApi analyseResponseObject];
        [self userInfoDic];
        [self.tableView reloadData];
    } failure:nil];
    
}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.dataSource[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return px1920Height(263);
    }
    else
    {
        return px1920Height(150);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *titleArray = self.dataSource[indexPath.section];
    if (indexPath.section == 0)
    {
        AvatarTableViewCell *cell = [AvatarTableViewCell dequeueReusableWithTableView:tableView];
        cell.titleLabel.text = titleArray[indexPath.row];
        [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:EXRACT_OBJECT(IMAGE)] placeholderImage:imageWithName(@"icon_head")];
        NSLog(@"%@",EXRACT_OBJECT(IMAGE));
        return cell;
    }
    else
    {
        MyInfoTableViewCell *cell = [MyInfoTableViewCell dequeueReusableWithTableView:tableView];
        cell.titleLabel.text = titleArray[indexPath.row];
        switch (indexPath.row) {
            case 0:
                cell.infoLabel.text = self.userInfoDic[@"nickname"];
                break;
            case 1:
                cell.infoLabel.text = [self getAgeWithDateString:self.userInfoDic[@"birthday"]];
                break;
            case 2:
            {
                if ([self.userInfoDic[@"sex"]isEqualToString:@"1"]) {
                    cell.infoLabel.text = @"男";
                }else if ([self.userInfoDic[@"sex"]isEqualToString:@"2"]) {
                    cell.infoLabel.text = @"女";
                }
                
            }
                break;
            default:
                break;
        }
        return cell;
    }
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0)
    {

        UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄照片" otherButtonTitles:@"相册", nil] ;
        [sheet showInView:self.view];

    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
            {
                NicknameViewController *vc = [NicknameViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1:
            {
                AgeViewController *vc = [AgeViewController new];
                vc.age = [self getAgeWithDateString:_userInfoDic[@"birthday"]];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2:
            {
                SexViewController *vc = [SexViewController new];
                vc.sex = [self.userInfoDic[@"sex"] intValue] - 1;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
    }

}

#pragma mark --- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        [superView addSubview:_tableView];
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (NSArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = @[@[@"头像"],@[@"昵称",@"年龄",@"性别"]];
    }
    return _dataSource;
}

- (UIButton *)exitButton
{
    if(!_exitButton)
    {
        UIView *superView = self.view;
        _exitButton = [[UIButton alloc]init];
        [superView addSubview:_exitButton];
        [_exitButton setTitle:@"退出" forState:UIControlStateNormal];
        [_exitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_exitButton.titleLabel setFont:fontCommonSize];
        [_exitButton setBackgroundColor:rgba(251,74,79,1)];
        _exitButton.layer.cornerRadius = 5;
        [_exitButton addTarget:self action:@selector(didClickExitButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exitButton;
}



#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(superView.mas_bottom).with.offset(-px1920Height(100));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.height.mas_equalTo(px1920Height(136));
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(252));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.bottom.mas_equalTo(self.exitButton.mas_top);
    }];
    

}

#pragma mark --- 设置导航栏
- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"我的资料"];
}

@end
